package com.lfd.rocketmq.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.rocketmq.service
 * @文件名: ProducerRockMQ
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/9/30 21:42
 * @描述：2. 生产者代码(同步)
 */
@Slf4j
@Service
public class ProducerProducerRockMQ {
   @Autowired
   private ObjectMapper objectMapper;

    /**
     *
     * @param namesrvAddr 如"127.0.0.1:9876"
     * @param topic
     * @param tag
     * @param msg
     * @throws MQClientException
     * @throws MQBrokerException
     * @throws RemotingException
     * @throws InterruptedException
     * @throws JsonProcessingException
     */
    public void send(String namesrvAddr,String topic, String tag, String msg) throws MQClientException, MQBrokerException, RemotingException, InterruptedException, JsonProcessingException {
        // 创建生产者并指定生产者组
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer(topic);
        defaultMQProducer.setNamesrvAddr(namesrvAddr);
        defaultMQProducer.start();
        for (int i = 0; i < 10; i++) {
            // 创建消息，指定主题、标签和消息体
            Message message = new Message(topic, tag, (msg+i).getBytes());
            //发送消息
            SendResult send = defaultMQProducer.send(message);
            String json = objectMapper.writeValueAsString(send);
            log.info("ProducerRockMQ send msg:{}", json);

        }
    }
}
